package com.huarui.part.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.ewaf.framework.model.ListModel;
import org.ewaf.framework.service.BaseService;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;

import com.huarui.dictionary.DictionaryEnum;
import com.huarui.dictionary.model.Dictionary;
import com.huarui.dictionary.service.DictionaryReadOnlyService;
import com.huarui.initial.service.InitialService;
import com.huarui.part.dao.IPartDao;
import com.huarui.part.dao.IPartUploadDao;
import com.huarui.part.model.Part;
import com.huarui.part.model.PartUpload;
import com.huarui.part.util.PartOperateResultEnum;
import com.huarui.user.model.SessionMessage;
import com.huarui.util.PinyinToolkit;

public class PartUploadService extends BaseService {

	private final static Logger logger = Logger.getLogger(InitialService.class);

	private IPartUploadDao getDao() {
		return (IPartUploadDao) dao;
	}

	private IPartDao partDao;

	private DictionaryReadOnlyService dictionaryReadOnlyService;

	@SuppressWarnings("unchecked")
	public Map<String, Object> save(final PartUpload partUpload) {
		Map<String, Object> resultMap = (Map<String, Object>) transactionTemplate
				.execute(new TransactionCallback() {
					Map<String, Object> resultMap = new HashMap<String, Object>();

					@Override
					public Object doInTransaction(TransactionStatus status) {
						try {

							partUpload.setStatus(PartUpload.STATUS_CREATE);
							Part part = partDao.getPartByCode(partUpload
									.getCode());

							if (part == null) {
								getDao().create(partUpload);
								resultMap.put(
										PartOperateResultEnum.SUCCESS.getMsg(),
										true);
								resultMap.put("msg",
										PartOperateResultEnum.OK_MSG_SUCCESS
												.getMsg());
							} else {
								resultMap.put(
										PartOperateResultEnum.SUCCESS.getMsg(),
										false);
								resultMap.put("msg",
										PartOperateResultEnum.ERROR_MSG_HASPART
												.getMsg());
							}

						} catch (Exception e) {
							logger.error("partUpload增加保存错误", e);
							status.setRollbackOnly();
							resultMap.put(PartOperateResultEnum.SUCCESS
									.getMsg(),
									PartOperateResultEnum.ERROR_MSG_DATABASE
											.getMsg());
						}

						return resultMap;
					}
				});
		return resultMap;
	}

	@SuppressWarnings("unchecked")
	public Map<String, Object> upadte(final PartUpload partUpload) {
		Map<String, Object> resultMap = (Map<String, Object>) transactionTemplate
				.execute(new TransactionCallback() {

					Map<String, Object> resultMap = new HashMap<String, Object>();

					@Override
					public Object doInTransaction(TransactionStatus status) {
						try {

							Part part = partDao.getPartByCode(partUpload
									.getCode());
							if (part != null) {
								partUpload.setErrorMsg("编码重复");
							} else {
								partUpload.setErrorMsg(null);
							}

							partUpload.setStatus(PartUpload.STATUS_CREATE);
							getDao().update(partUpload);
							resultMap.put(
									PartOperateResultEnum.SUCCESS.getMsg(),
									true);
							resultMap.put("msg",
									PartOperateResultEnum.OK_MSG_SUCCESS
											.getMsg());

						} catch (Exception e) {
							logger.error("partUpload更新保存错误", e);
							status.setRollbackOnly();
							resultMap.put(PartOperateResultEnum.SUCCESS
									.getMsg(),
									PartOperateResultEnum.ERROR_MSG_DATABASE
											.getMsg());
						}

						return resultMap;
					}
				});
		return resultMap;
	}

	public ListModel<PartUpload> getPartUploadListByComId(
			ListModel<PartUpload> lm, int companyId, Map<String, Object> map) {

		map.put("start", lm.getStart());
		map.put("pageSize", lm.getPageSize());
		Integer count = getDao().getCountPartUploadByComId(map);

		lm.setTotal(count);

		List<PartUpload> list = getDao().getPartUploadListByComId(map);

		lm.setResult(list);

		return lm;
	}

	@SuppressWarnings("unchecked")
	public Map<String, Object> save(final List<PartUpload> list) {
		Map<String, Object> resultMap = (Map<String, Object>) transactionTemplate
				.execute(new TransactionCallback() {
					Map<String, Object> resultMap = new HashMap<String, Object>();

					@Override
					public Object doInTransaction(TransactionStatus status) {
						try {

							for (PartUpload partUpload : list) {
								partUpload.setStatus(PartUpload.STATUS_CREATE);
								Part part = partDao.getPartByCode(partUpload
										.getCode());
								if (part != null) {
									partUpload.setErrorMsg("编码重复");
								}
								if (partUpload.getName().length() == 0) {
									if (partUpload.getErrorMsg() == null) {
										partUpload.setErrorMsg("名称为空");
									} else {

										partUpload.setErrorMsg(partUpload
												.getErrorMsg() + "/名称为空");
									}

								}
								getDao().create(partUpload);
								resultMap.put(
										PartOperateResultEnum.SUCCESS.getMsg(),
										true);
								resultMap
										.put(PartOperateResultEnum.RESULT_TYPE_SUCCESS
												.getMsg(), "ok");
								resultMap.put("msg",
										PartOperateResultEnum.OK_MSG_SUCCESS
												.getMsg());

							}

						} catch (Exception e) {
							logger.error("partUpload增加保存错误", e);
							status.setRollbackOnly();
							resultMap.put(PartOperateResultEnum.SUCCESS
									.getMsg(),
									PartOperateResultEnum.ERROR_MSG_DATABASE
											.getMsg());
						}

						return resultMap;
					}
				});
		return resultMap;
	}

	@SuppressWarnings("unchecked")
	public Map<String, Object> deleteWithComId(final List<Integer> list,
			final SessionMessage sm) {
		Map<String, Object> resultMap = (Map<String, Object>) transactionTemplate
				.execute(new TransactionCallback() {

					Map<String, Object> resultMap = new HashMap<String, Object>();

					@Override
					public Object doInTransaction(TransactionStatus status) {
						try {

							for (Integer id : list) {
								Map<String, Object> map = new HashMap<String, Object>();
								map.put("id", id);
								map.put("companyId", sm.getCompanyId());

								map.put("status", PartUpload.STATUS_SUBMIT);

								getDao().deleteWithCompanyId(map);
							}

						} catch (Exception e) {
							logger.error("删除partupload错误", e);
							resultMap.put(PartOperateResultEnum.SUCCESS
									.getMsg(),
									PartOperateResultEnum.ERROR_MSG_DATABASE
											.getMsg());
							status.setRollbackOnly();
							return resultMap;
						}
						resultMap.put(PartOperateResultEnum.SUCCESS.getMsg(),
								true);
						return resultMap;
					}
				});
		return resultMap;
	}

	public PartUpload getPartUploadById(Integer id) {

		return (PartUpload) getDao().getById(id);
	}

	@SuppressWarnings("unchecked")
	public Map<String, Object> submit(final List<Integer> list,
			final SessionMessage sm) {
		Map<String, Object> resultMap = (Map<String, Object>) transactionTemplate
				.execute(new TransactionCallback() {

					Map<String, Object> resultMap = new HashMap<String, Object>();

					@Override
					public Object doInTransaction(TransactionStatus status) {
						try {

							for (Integer id : list) {

								PartUpload partUpload = (PartUpload) getDao()
										.getById(id);
								if (partUpload != null) {

									if (partUpload.getStatus().equals(
											PartUpload.STATUS_CREATE)
											&& partUpload.getCompanyId()
													.equals(sm.getCompanyId())) {
										partUpload
												.setStatus(PartUpload.STATUS_SUBMIT);
										getDao().update(partUpload);
									}
								}

							}
							resultMap.put(
									PartOperateResultEnum.SUCCESS.getMsg(),
									true);
							resultMap.put("msg",
									PartOperateResultEnum.OK_MSG_SUCCESS
											.getMsg());

						} catch (Exception e) {
							logger.error("partUpload提交保存错误", e);
							status.setRollbackOnly();
							resultMap.put(PartOperateResultEnum.SUCCESS
									.getMsg(),
									PartOperateResultEnum.ERROR_MSG_DATABASE
											.getMsg());
						}

						return resultMap;
					}
				});
		return resultMap;
	}

	public ListModel<PartUpload> getAllPartUploadListByConditions(
			ListModel<PartUpload> lm, Map<String, Object> map) {

		map.put("start", lm.getStart());

		map.put("pageSize", lm.getPageSize());

		Integer count = getDao().getPartUloadCountByConditions(map);

		lm.setTotal(count);

		List<PartUpload> list = getDao().getPartUploadListByConditions(map);

		lm.setResult(list);

		return lm;
	}

	@SuppressWarnings("unchecked")
	public Map<String, Object> submitToPart(final Part part, final int id) {
		Map<String, Object> resultMap = (Map<String, Object>) transactionTemplate
				.execute(new TransactionCallback() {

					Map<String, Object> resultMap = new HashMap<String, Object>();

					@Override
					public Object doInTransaction(TransactionStatus status) {
						try {

							// 判断是否已经处理过
							PartUpload partUpload = (PartUpload) getDao()
									.getById(id);
							if (partUpload.getStatus().equals(
									PartUpload.STATUS_SUBMIT)) {

								// 先查询编码是否已经存在
								Part p = partDao.getPartByCode(part.getCode());

								if (p == null) {

									// 更新PartUpload表

									partUpload
											.setStatus(PartUpload.STATUS_SUCCESSED);
									partUpload.setErrorMsg(null);

									partUpload.setCode(part.getCode());
									partUpload.setMeasurementUnit(part
											.getMeasurementUnit());
									partUpload.setName(part.getName());
									partUpload.setNameEn(part.getNameEn());
									getDao().update(partUpload);

									// 增加到part表
									List<Dictionary> listSource = dictionaryReadOnlyService
											.getDictionaryByGroup(DictionaryEnum.GROUP_SOURCE);

									part.setId(null);
									for (Dictionary dictionary : listSource) {
										part.setDurability("0");
										part.setSource(dictionary.getVarIndex());
										part.setCompanyId(partUpload
												.getCompanyId());
										part.setPyCode(PinyinToolkit
												.cn2FirstSpell(part.getName()));
										partDao.create(part);
									}

									resultMap.put(PartOperateResultEnum.SUCCESS
											.getMsg(), true);
									resultMap
											.put("msg",
													PartOperateResultEnum.OK_MSG_SUCCESS
															.getMsg());
								} else {

									resultMap.put(PartOperateResultEnum.SUCCESS
											.getMsg(), false);
									resultMap
											.put("msg",
													PartOperateResultEnum.ERROR_MSG_HASPART
															.getMsg());
								}

							} else {

								resultMap.put(
										PartOperateResultEnum.SUCCESS.getMsg(),
										false);
								resultMap
										.put("msg",
												PartOperateResultEnum.RROR_MSG_STATES_HASSUBMIT
														.getMsg());

							}

						} catch (Exception e) {
							logger.error("part 增加新零件保存错误", e);
							status.setRollbackOnly();
							resultMap.put(
									PartOperateResultEnum.SUCCESS.getMsg(),
									false);
							resultMap.put("msg",
									PartOperateResultEnum.ERROR_MSG_DATABASE
											.getMsg());
						}

						return resultMap;
					}
				});
		return resultMap;
	}

	@SuppressWarnings("unchecked")
	public Map<String, Object> noPass(final Integer id, final String errMsg) {
		Map<String, Object> resultMap = (Map<String, Object>) transactionTemplate
				.execute(new TransactionCallback() {

					Map<String, Object> resultMap = new HashMap<String, Object>();

					@Override
					public Object doInTransaction(TransactionStatus status) {
						try {

							// 判断是否已经处理过
							PartUpload partUpload = (PartUpload) getDao()
									.getById(id);
							if (partUpload.getStatus().equals(
									PartUpload.STATUS_SUBMIT)) {

								partUpload.setStatus(PartUpload.STATUS_FAILURE);
								partUpload.setErrorMsg(errMsg);
								getDao().update(partUpload);

								resultMap.put(
										PartOperateResultEnum.SUCCESS.getMsg(),
										true);
								resultMap.put("msg",
										PartOperateResultEnum.OK_MSG_SUCCESS
												.getMsg());

							} else {

								resultMap.put(
										PartOperateResultEnum.SUCCESS.getMsg(),
										false);
								resultMap
										.put("msg",
												PartOperateResultEnum.RROR_MSG_STATES_HASSUBMIT
														.getMsg());

							}

						} catch (Exception e) {
							logger.error("partUpload 审核不通过保存错误", e);
							status.setRollbackOnly();
							resultMap.put(
									PartOperateResultEnum.SUCCESS.getMsg(),
									false);
							resultMap.put("msg",
									PartOperateResultEnum.ERROR_MSG_DATABASE
											.getMsg());
						}

						return resultMap;
					}
				});
		return resultMap;
	}

	public void setPartDao(IPartDao partDao) {
		this.partDao = partDao;
	}

	public void setDictionaryReadOnlyService(
			DictionaryReadOnlyService dictionaryReadOnlyService) {
		this.dictionaryReadOnlyService = dictionaryReadOnlyService;
	}

}
